import base64
import logging
from flask import Blueprint, render_template, request, jsonify
from bilibili_api import search, sync, video
from exts import db
from models import MonitoringTask, MonitoredVideo, Comment
import requests

base_bp = Blueprint("base", __name__, url_prefix="/")


@base_bp.route("/")
def views():
    # 在需要查看连接池状态的时候，可以调用get_pool_status()方法
    # pool_status = db.session.connection().engine.pool.status()
    # print(pool_status)
    """返回首页前端"""
    # get_hot()
    return render_template("index.html")


# 返回十个热门话题接口
@base_bp.route("/get_hot")
def get_hot():
    response = {}
    try:
        url = 'https://api.bilibili.com/x/web-interface/wbi/search/square?limit=10'
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/'
                          '58.0.3029.110 Safari/537.3'
        }
        response = requests.get(url, headers=headers)

        if response.status_code == 200:
            data = response.json()
            return data, 200
        else:
            response['status'] = 'error'
            response['message'] = '请求热搜失败，状态码：' + str(response.status_code)
            return jsonify(response), 404
    except Exception as e:
        logging.error("An error occurred: %s", e)  # 使用logging记录错误
        response['status'] = 'error'
        response['message'] = '操作失败'
        return jsonify(response), 500  # 发生异常，返回500状态码表示服务器内部错误


# 搜索视频接口
@base_bp.route("/topics_search")
def topics_search():
    keyword = request.args.get('keyword', '')  # 获取名为'keyword'的查询参数
    data = sync(search.search(keyword))
    video = ''
    for i in data.get('result'):
        if i.get('result_type') == 'video':
            video = i.get('data')
    for video_item in video:
        video_item['pic'] = "https:" + video_item['pic']
    return jsonify('video', video)


# 视频封面图片的代理
@base_bp.route('/proxy_image', methods=['POST'])
def proxy_image():
    try:
        # 从POST请求中获取图片URL
        image_url = request.form.get('imageUrl')

        # 使用requests库发送GET请求获取图片数据
        image_response = requests.get(image_url)

        # 检查是否成功获取了图片数据
        if image_response.status_code == 200:
            # 将图片数据以Base64编码的形式返回给前端
            image_base64 = base64.b64encode(image_response.content).decode('utf-8')
            return jsonify({'imageData': image_base64})
        else:
            return jsonify({'error': 'Failed to fetch image'})

    except Exception as e:
        return jsonify({'error': str(e)})


@base_bp.route('/report/<rpid>')
def banned_comment(rpid):
    comment = Comment.query.filter_by(rpid=rpid).first()
    comment.is_banned = True
    db.session.commit()
    return jsonify({'success': 'success'}), 200


# 展示自建话题监控任务
@base_bp.route('/show_topic_tasks')
def get_topic_tasks():
    try:
        tasks = MonitoringTask.query.filter_by(task_type='自建话题').all()
        task_list = [task.__dict__ for task in tasks]
        for task in task_list:
            del task['_sa_instance_state']
        return jsonify({'data': {'task': task_list}}), 200
    except Exception as e:
        return jsonify({'error': 'Failed to fetch zone monitoring tasks'}), 500


# 展示自建视频监控任务
@base_bp.route('/show_video_tasks')
def get_video_tasks():
    try:
        tasks = MonitoringTask.query.filter_by(task_type='自建视频').all()
        task_list = [task.__dict__ for task in tasks]
        for task in task_list:
            del task['_sa_instance_state']
        return jsonify({'data': {'task': task_list}}), 200
    except Exception as e:
        return jsonify({'error': 'Failed to fetch zone monitoring tasks'}), 500


# 展示热搜话题监控任务
@base_bp.route('/show_hot_tasks')
def get_hot_tasks():
    try:
        tasks = MonitoringTask.query.filter_by(task_type='热搜话题').all()
        task_list = [task.__dict__ for task in tasks]
        for task in task_list:
            del task['_sa_instance_state']
        return jsonify({'data': {'task': task_list}}), 200
    except Exception as e:
        return jsonify({'error': 'Failed to fetch zone monitoring tasks'}), 500


# 展示类别视频监控任务
@base_bp.route('/show_zone_tasks')
def get_zone_tasks():
    try:
        tasks = MonitoringTask.query.filter_by(task_type='zone').all()
        task_list = [task.__dict__ for task in tasks]
        for task in task_list:
            del task['_sa_instance_state']
        return jsonify({'data': {'task': task_list}}), 200
    except Exception as e:
        return jsonify({'error': 'Failed to fetch zone monitoring tasks'}), 500


@base_bp.route('/alert_detail/<bvid>')
def get_video_violence_comment(bvid):
    video_detail = MonitoredVideo.query.filter_by(bvid=bvid).first().__dict__
    del video_detail['_sa_instance_state']
    return render_template('video_violence_comment_show.html', video_detail=video_detail)

